const BaseWidget = require('../../core/BaseWidget');
const path = require('path');
const TodoDatabase = require('./database');

class TodoWidget extends BaseWidget {
    static displayName = 'Todo List';
    static icon = 'fa-tasks';
    static description = 'Track your tasks and goals';
    
    constructor(id, config = {}) {
        super(id, config);
        this.todos = [];
        this.loadI18n();
    }

    async loadI18n() {
        try {
            const lang = this.config.language || 'en';
            const i18nPath = path.join(__dirname, 'locales', `${lang}.json`);
            delete require.cache[require.resolve(i18nPath)];
            this.i18n = require(i18nPath);
        } catch (error) {
            // Fallback to English
            const i18nPath = path.join(__dirname, 'locales', 'en.json');
            delete require.cache[require.resolve(i18nPath)];
            this.i18n = require(i18nPath);
        }
    }

    getName() {
        return 'TodoWidget';
    }

    getVersion() {
        return '1.0.0';
    }

    getDescription() {
        return this.i18n.description;
    }

    async initialize() {
        // Load todos from database
        const dbManager = this.getDatabaseManager();
        if (dbManager) {
            const todoDb = dbManager.getWidgetDatabase('todo');
            if (todoDb) {
                this.todos = await todoDb.getTodos(this.id);
            }
        }
    }

    async addTodo(text, priority = 'medium') {
        const dbManager = this.getDatabaseManager();
        if (dbManager) {
            const todoDb = dbManager.getWidgetDatabase('todo');
            if (todoDb) {
                const todo = await todoDb.addTodo(this.id, text, priority);
                this.todos.push(todo);
                return todo;
            }
        }
        
        // Fallback to in-memory storage
        const todo = {
            id: Date.now().toString(),
            text,
            priority,
            completed: false,
            createdAt: new Date().toISOString()
        };
        this.todos.push(todo);
        this.updateData({ todos: this.todos });
        return todo;
    }

    async toggleTodo(id) {
        const dbManager = this.getDatabaseManager();
        if (dbManager) {
            const todoDb = dbManager.getWidgetDatabase('todo');
            if (todoDb) {
                const result = await todoDb.toggleTodo(id);
                if (result) {
                    // Update local todos array
                    const todo = this.todos.find(t => t.id === id);
                    if (todo) {
                        todo.completed = !todo.completed;
                    }
                }
                return result;
            }
        }
        
        // Fallback to in-memory storage
        const todo = this.todos.find(t => t.id === id);
        if (todo) {
            todo.completed = !todo.completed;
            this.updateData({ todos: this.todos });
            return true;
        }
        return false;
    }

    async deleteTodo(id) {
        const dbManager = this.getDatabaseManager();
        if (dbManager) {
            const todoDb = dbManager.getWidgetDatabase('todo');
            if (todoDb) {
                const result = await todoDb.deleteTodo(id);
                if (result) {
                    // Update local todos array
                    this.todos = this.todos.filter(t => t.id !== id);
                }
                return result;
            }
        }
        
        // Fallback to in-memory storage
        const index = this.todos.findIndex(t => t.id === id);
        if (index > -1) {
            this.todos.splice(index, 1);
            this.updateData({ todos: this.todos });
            return true;
        }
        return false;
    }

    async getStats() {
        const dbManager = this.getDatabaseManager();
        if (dbManager) {
            const todoDb = dbManager.getWidgetDatabase('todo');
            if (todoDb) {
                return await todoDb.getTodoStats(this.id);
            }
        }
        
        // Fallback to in-memory calculation
        const total = this.todos.length;
        const completed = this.todos.filter(t => t.completed).length;
        const pending = total - completed;
        return { total, completed, pending };
    }

    render() {
        const stats = this.getStats();
        return `
            <div class="todo-widget" data-widget-id="${this.id}">
                <div class="todo-header">
                    <h3>${this.i18n.title}</h3>
                    <button class="add-todo-btn" onclick="window.widgetManager.executeWidgetAction('${this.id}', 'showAddTodoModal', {})">
                        <i class="fas fa-plus"></i> ${this.i18n.addTask}
                    </button>
                </div>
                <div class="todo-list" id="todo-list-${this.id}">
                    ${this.todos.map(todo => this.renderTodoItem(todo)).join('')}
                </div>
                <div class="todo-stats">
                    <span>${this.i18n.completed}: <span id="completed-count-${this.id}">${stats.completed}</span></span>
                    <span>${this.i18n.pending}: <span id="pending-count-${this.id}">${stats.pending}</span></span>
                </div>
            </div>
            ${this.renderAddTodoModal()}
        `;
    }

    renderTodoItem(todo) {
        return `
            <div class="todo-item ${todo.completed ? 'completed' : ''}" data-todo-id="${todo.id}">
                <input type="checkbox" class="todo-checkbox" ${todo.completed ? 'checked' : ''} 
                       onchange="window.widgetManager.executeWidgetAction('${this.id}', 'toggleTodo', { todoId: '${todo.id}' })">
                <span class="todo-text">${todo.text}</span>
                <span class="todo-priority ${todo.priority}">${this.i18n.priority[todo.priority]}</span>
                <div class="todo-actions">
                    <button class="todo-btn delete" onclick="window.widgetManager.executeWidgetAction('${this.id}', 'deleteTodo', { todoId: '${todo.id}' })">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
    }

    updateStats() {
        const stats = this.getStats();
        // This will be called by the frontend to update stats
        return stats;
    }

    renderAddTodoModal() {
        return `
            <div class="add-todo-modal" id="add-todo-modal-${this.id}" style="display: none;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>${this.i18n.addTask}</h3>
                        <button class="close-btn" onclick="window.widgetManager.executeWidgetAction('${this.id}', 'hideAddTodoModal', {})">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="add-todo-form-${this.id}" onsubmit="window.widgetManager.executeWidgetAction('${this.id}', 'handleAddTodo', { event: event, widgetId: '${this.id}' }); return false;">
                            <div class="form-group">
                                <label>${this.i18n.taskText}</label>
                                <input type="text" id="todo-text-${this.id}" required 
                                       placeholder="${this.i18n.taskPlaceholder}">
                            </div>
                            <div class="form-group">
                                <label>${this.i18n.priority}</label>
                                <select id="todo-priority-${this.id}">
                                    <option value="high">${this.i18n.priority.high}</option>
                                    <option value="medium" selected>${this.i18n.priority.medium}</option>
                                    <option value="low">${this.i18n.priority.low}</option>
                                </select>
                            </div>
                            <div class="form-actions">
                                <button type="submit" class="submit-btn">
                                    <i class="fas fa-plus"></i> ${this.i18n.addTask}
                                </button>
                                <button type="button" class="cancel-btn" onclick="window.widgetManager.executeWidgetAction('${this.id}', 'hideAddTodoModal', {})">
                                    ${this.i18n.cancel}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        `;
    }

    destroy() {
        // Cleanup if needed
        super.destroy();
    }

    // Internal action handlers
    showAddTodoModal() {
        const modal = document.getElementById(`add-todo-modal-${this.id}`);
        if (modal) {
            modal.style.display = 'block';
            document.getElementById(`todo-text-${this.id}`).focus();
        }
    }

    hideAddTodoModal() {
        const modal = document.getElementById(`add-todo-modal-${this.id}`);
        if (modal) {
            modal.style.display = 'none';
            const form = document.getElementById(`add-todo-form-${this.id}`);
            if (form) {
                form.reset();
            }
        }
    }

    async handleAddTodo(params) {
        const { event } = params;
        event.preventDefault();
        
        const text = document.getElementById(`todo-text-${this.id}`).value;
        const priority = document.getElementById(`todo-priority-${this.id}`).value;
        
        try {
            await this.addTodo(text, priority);
            this.hideAddTodoModal();
            this.refreshWidget();
        } catch (error) {
            console.error('Error adding todo:', error);
            alert('Error adding todo');
        }
    }

    async toggleTodoFromWidget(params) {
        const { todoId } = params;
        try {
            await this.toggleTodo(todoId);
            this.refreshWidget();
        } catch (error) {
            console.error('Error toggling todo:', error);
        }
    }

    async deleteTodoFromWidget(params) {
        const { todoId } = params;
        if (!confirm('Are you sure you want to delete this todo?')) {
            return;
        }
        
        try {
            await this.deleteTodo(todoId);
            this.refreshWidget();
        } catch (error) {
            console.error('Error deleting todo:', error);
            alert('Error deleting todo');
        }
    }

    refreshWidget() {
        // Refresh the widget by updating its content
        const widgetContent = document.getElementById(`widget-content-${this.id}`);
        if (widgetContent) {
            widgetContent.innerHTML = this.render();
        }
    }
}

module.exports = TodoWidget;